class Controls:
    'Handels ingame key events , redirects events to player or menu.'
    def __init__(self,keys,player,menu):
        ' keys is an hash with {action_name:key}, player and menu should support left,right,up,down interface'
        self.selecting = 0
        self.player = player
        self.menu = menu
        self.listner = self.player

        keymap = {}
        keymap[keys['left']]    = self._left
        keymap[keys['right']]   = self._right
        keymap[keys['up']]      = self._up
        keymap[keys['down']]    = self._down
        keymap[keys['fire1']]    = self._fire1
        keymap[keys['fire2']]    = self._fire2
        self.keymap = keymap
   
    def _left(self,dt):
        self.listner.left(dt)

    def _right(self,dt):
        self.listner.right(dt)

    def _up(self,dt):
        # exit menu mode if we are at top of menu
        if self.menu.isAtRoot() and self.menu.keyReady():
            self.selecting = 0
            self.listner = self.player
        self.listner.up(dt)

    def _enableMenu(self):
        if not self.selecting:
            self.selecting = 1
            self.menu.reset()
            self.listner = self.menu
        
    def _down(self,dt):
        self.listner.down(dt)

    def _fire1(self,dt):
        self.listner.fire1(dt)

    def _fire2(self,dt):
        self.listner.down(dt)
    
    def update(self,key_state,dt):
        ''' update the player/menu according to key_state '''
        if not self.player.ship.alive(): return

        if self.selecting and not self.player.isDocked():
            self.selecting = 0
            self.listner = self.player
        keymap = self.keymap
        # loop the control bindings and call the bound method
        for key in self.keymap.keys(): 
            if key_state[key]:
                keymap[key](dt)
        self.player.selecting = self.selecting
